package com.kuqi.core;

import android.app.Activity;
import android.app.Application;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Message;

import com.kuqi.common.APPCONST;
import com.kuqi.entitiy.UpdateInfo;
import com.kuqi.http.HttpCmd;
import com.kuqi.http.HttpHelper;
import com.kuqi.utils.CacheHelper;

public class PersistentFuncWorker {


    /**
     * 定义支线程发送命令方法
     * @param cmd Http 命令实体
     */
    public void SendHttp(final HttpCmd cmd){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String response = HttpHelper.PostJsonString(cmd.getTargetUrl(), cmd.getRequestJson());
                Message msg = cmd.getMaster().obtainMessage();
                msg.what = cmd.getKey();
                msg.obj = response;
                cmd.getMaster().sendMessage(msg);
            }
        }).start();
    }


    /**
     * 检验网络-服务器是否可用的方法
     * @param cmd Http 命令实体
     */
    public void CheckHttp(final HttpCmd cmd){
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean can_connect = HttpHelper.isConnByHttp(cmd.getTargetUrl());
                Message msg = cmd.getMaster().obtainMessage();
                msg.what = cmd.getKey();
                msg.obj = can_connect;
                cmd.getMaster().sendMessage(msg);
            }
        }).start();
    }


    /**
     * 获取app版本号
     * @return int
     */
    public int getVersionCode(Application application) {
        try {
            PackageManager manager = application.getPackageManager();
            PackageInfo info = manager.getPackageInfo(application.getPackageName(), 0);
            return info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 获取app版本号（别称）(String)
     * @return string
     */
    public String getStrVersionName(Application application) {
        try {
            PackageManager manager = application.getPackageManager();
            PackageInfo info = manager.getPackageInfo(application.getPackageName(), 0);
            return info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return "1.0.0";
        }
    }


    /**
     * 检查更新
     */
    public void checkVersion(Activity activity, Application application) {
        UpdateInfo updateInfo = (UpdateInfo) CacheHelper.readObject(APPCONST.FILE_NAME_UPDATE_INFO);
        int versionCode = getVersionCode(application);
        if (updateInfo != null) {
            if (updateInfo.getNewestVersionCode() > versionCode) {
                updateApp(activity, updateInfo.getDownLoadUrl(), versionCode);
            }
        }
    }


    /**
     * 进行更新
     */
    public void updateApp(final Activity activity, final String url, final int versionCode) {
        // TODO 更新功能的完成
    }


}
